package com.onion.mvc.resolver;

import com.onion.utils.surface.PageVo;
import com.onion.utils.utils.StringHelper;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class PageParamResolver implements HandlerMethodArgumentResolver {

    private String KEY_PAGE_NO = "pageNo";
    private String KEY_PAGE_SIZE = "pageSize";
    private int defaultPageSize = 15;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        Class<?> paramType = parameter.getParameterType();
        return PageVo.class.isAssignableFrom(paramType);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String strPageNo = webRequest.getParameter(KEY_PAGE_NO);
        String strPageSize = webRequest.getParameter(KEY_PAGE_SIZE);
        int pageNo = StringHelper.str2Int(strPageNo, 0);
        int pageSize = StringHelper.str2Int(strPageSize, defaultPageSize);
        return PageVo.instance(pageNo, pageSize);
    }

}